<?php
/*
    Copyright (C) 2008 - 2010 Inanta Martsanto
    
    This file is part of Koma.

    Koma is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Koma is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Koma.  If not, see <http://www.gnu.org/licenses/>.
    
    Inanta Martsanto (inanta@inationsoft.com)
*/

class KomaUploadHandler extends KomaSingletonObject
{
    private $_counter = 1;
    
    function __construct()
    {
	$this->createProperties(array('Filename' => '',
				      'Type' => '',
				      'TemporaryFilename' => '',
				      'Error' => 0,
				      'Size' => 0));
    }
    
    function handle($name, $upload_dir = null , $upload_name = null)
    {
	if(is_array($_FILES[$name]['name']))
	{
	    if($upload_dir == null) $upload_dir = KOMA_ROOT_PATH.'/uploads';

	    foreach ($_FILES[$name]["error"] as $key => $error)
	    {
		if ($error == UPLOAD_ERR_OK)
		{
		    if (!move_uploaded_file($_FILES[$name]["tmp_name"][$key], $upload_dir.'/'.$_FILES[$name]["name"][$key])) return false;
		}
	    }
	}
	else
	{
	    $this->initialize($name);
	    
	    if($upload_dir == null) $upload_dir = KOMA_ROOT_PATH.'/uploads';
	    if($upload_name == null) $upload_name = basename($this->Filename);
    
	    if (!move_uploaded_file($this->TemporaryFilename, $upload_dir.'/'.$upload_name)) return false;
	}
	
	return true;
    }
    
    private function initialize($name)
    {
	if(is_array($_FILES[$name]['name']))
	{
	    $this->Error = $_FILES[$name]['error'][$this->_counter];
	    $this->Filename = $_FILES[$name]['name'][$this->_counter];
	    $this->Size = $_FILES[$name]['size'][$this->_counter];
	    $this->TemporaryFilename = $_FILES[$name]['tmp_name'][$this->_counter];
	    $this->Type = $_FILES[$name]['type'][$this->_counter];
	    
	    $this->_counter++;
	}
	else
	{
	    $this->Error = $_FILES[$name]['error'];
	    $this->Filename = $_FILES[$name]['name'];
	    $this->Size = $_FILES[$name]['size'];
	    $this->TemporaryFilename = $_FILES[$name]['tmp_name'];
	    $this->Type = $_FILES[$name]['type'];  
	}

    }
    
    static function getInstance()
    {
	return self::createInstance(__CLASS__);
    }
}
?>